//
//  JXTTransparentBarVC.m
//  ScrollScale
//
//  Created by JXT on 16/3/11.
//  Copyright © 2016年 JXT. All rights reserved.
//
//  ***
//  *   GitHub:https://github.com/kukumaluCN/JXT_iOS_Demos
//  *   博客:http://www.jianshu.com/users/c8f8558a4b1d/latest_articles
//  *   邮箱:1145049339@qq.com
//  ***

#import "CWQ_inegralVC.h"
#import "CWQ_integralHeadview.h"
#import "CWQ_titleContentCell.h"
#import "CWQ_tableView.h"
#import "BTBaseWebVC.h"
#import "UIImageView+BTimageView.h"
#define pictureHeight 230
static NSString * const cellId = @"CWQ_titleContentCellID";

@interface CWQ_inegralVC () <UITableViewDelegate>

@property(nonatomic, strong)CWQ_tableView *tableView;
//上拉加载的页面
@property (nonatomic, assign) NSInteger page;


@property(nonatomic, strong)NSMutableArray *dataSource;


@property (nonatomic, strong) UIImageView * topImageView;

@property (nonatomic, assign) CGFloat topContentInset;

@property (nonatomic, assign) CGFloat alphaMemory;

@property (nonatomic, assign) BOOL statusBarStyleControl;

@property (nonatomic, strong) UIView *navBarView;
@property (nonatomic, strong) UIView *navBarBgView;

@property (nonatomic,  assign) BOOL loadSucess;

@end

@implementation CWQ_inegralVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView = [[CWQ_tableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight ) style:UITableViewStylePlain cellClass:@"CWQ_titleContentCell" vc:self upload:YES];
    _tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];
    _dataSource = [NSMutableArray array];
    _page = 1;
    [_tableView cwq_requestDataWithDown:YES];
    self.loadSucess = NO;
    _statusBarStyleControl = NO;
    
    [self createNavBar];
    [self createHeadView];
}

- (void)back {

    [self.navigationController popViewControllerAnimated:YES];

}

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    self.navBarView.alpha = 0;
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}


#pragma mark - 创建tableView
- (void)createNavBar {

    _navBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 64)];
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 44, 44)];
    [backBtn setImage:[UIImage imageNamed:@"back copy"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 10)];
    UILabel *titleLabel = [[UILabel alloc] init];
    [titleLabel setBounds:CGRectMake(0, 0, kScreenWidth - 44*2, 44)];
    titleLabel.center = CGPointMake(kScreenWidth/2, 42);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.tag = 111111;
    titleLabel.text = @"积分";
    titleLabel.hidden = YES;
    
    
    UIButton *helpBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [helpBtn setFrame:CGRectMake(kScreenWidth - 80, 20, 80, 44)];
    helpBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [helpBtn setTitle:@"使用帮助" forState:UIControlStateNormal];
    [helpBtn setTintColor:[UIColor whiteColor]];
    [helpBtn addTarget:self action:@selector(useHelp) forControlEvents:UIControlEventTouchUpInside];

    
    
    _navBarView.backgroundColor = kMainColor;
    
    _navBarBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 64)];

    [_navBarBgView addSubview:backBtn];
    [_navBarBgView addSubview:titleLabel];
    [_navBarBgView addSubview:helpBtn];
    [self.view addSubview:_navBarView];
    [self.view addSubview:_navBarBgView];
    
}




#pragma mark - 创建头像视图
- (void)createHeadView
{
    CWQ_integralHeadview * headBkView = [CWQ_integralHeadview headView];
    if (!self.score) {
        headBkView.integral.text  = @"0";
    }else{
       headBkView.integral.text = self.score;
    }
  
    [headBkView setFrame:CGRectMake(0, 0, kScreenWidth, 230)];
    _topImageView = [[UIImageView alloc] initWithFrame:headBkView.bounds];
    [headBkView.levelIcon bt_setImageWithUrl:self.leveliconUrl];
    /*
     重要的属性设置
     */
    //这个属性的值决定了 当视图的几何形状变化时如何复用它的内容 这里用 UIViewContentModeScaleAspectFill 意思是保持内容高宽比 缩放内容 超出视图的部分内容会被裁减 填充UIView
    _topImageView.contentMode = UIViewContentModeScaleAspectFill;
    // 这个属性决定了子视图的显示范围 取值为YES时，剪裁超出父视图范围的子视图部分.这里就是裁剪了_pictureImageView超出_header范围的部分.
    _topImageView.clipsToBounds = YES;
//    _topImageView.backgroundColor = kMainColor;
    [_topImageView setImage:[UIImage imageNamed:@"navitationbar"]];
    [headBkView insertSubview:_topImageView atIndex:0];
  
    self.tableView.tableHeaderView = headBkView;
}




- (void)useHelp {

    
    BTBaseWebVC *vc =[BTBaseWebVC new];
    vc.url = [NSString stringWithFormat:@"%@/%@",[BTNetworkManager sharedMg].bathURL ,kRewardHelp];
    [self.navigationController pushViewController:vc animated:YES];
 

}




- (void)viewDidLayoutSubviews
{
    [self.view bringSubviewToFront:_navBarView];
    [self.view bringSubviewToFront:_navBarBgView];
    [super viewDidLayoutSubviews];
}



- (void)setDataSource:(NSMutableArray *)dataSource {
    _dataSource = dataSource;
    [self.tableView setupSourceArray:self.dataSource];
}



- (void)cwq_tableView:(CWQ_tableView *)tableView requestDataWithDown:(BOOL)down {
    
    if (down) {
        self.page = 1;
    }else {
        self.page ++;
    }
    if (self.loadSucess == NO) {
         [self wsj_showLodingGif];
    }
   
    tableView.loading = YES;
    int count = 10;
    NSDictionary *param = @{@"page":@(self.page), @"rows":@(count)};
    defineWeakSelf;
    [[BTNetworkManager sharedMg] GET:BTMyIntegralUrl parameters:param success:^(id responseObject) {
        [weakSelf wsj_hideLodingGif];
        if (responseObject_success) {
            weakSelf.loadSucess = YES;
            NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *dict in responseObject[@"data"][@"data"]) {
                BTMyInegralM *model = [BTMyInegralM mj_objectWithKeyValues:dict];
                [arr addObject:model];
            }
            //判断是上拉刷新？  还是下拉加载？
            if (!down) {
                NSMutableArray *muArr = [weakSelf.dataSource mutableCopy];
                
                [muArr addObjectsFromArray:arr];
                weakSelf.dataSource = muArr;
                if ([responseObject[@"data"][@"totalPage"] isKindOfClass:[NSNull class]] || weakSelf.page == [responseObject[@"data"][@"totalPage"] integerValue]) {
                    tableView.footer.hidden = YES;
                }
                [tableView.footer endRefreshing];
            }else {
                
               
                if (![responseObject[@"data"][@"totalPage"] isKindOfClass:[NSNull class]] && weakSelf.page == [responseObject[@"data"][@"totalPage"] integerValue]) {
                    tableView.footer.hidden = YES;
                }else {
                    tableView.footer.hidden = NO;
                }
                self.dataSource = arr;
                [tableView.header endRefreshing];
            }
            if (self.dataSource.count<=0) {
                tableView.loading = NO;
            }
            
            [tableView reloadData];
            
        }
    } failure:^(NSString *err) {
        [weakSelf wsj_hideLodingGif];
        if (weakSelf.page > 1) {
            //上拉
            [tableView.footer endRefreshing];
            weakSelf.page -= 1;
        }else {
            //下拉
            [tableView.header endRefreshing];
            if (self.dataSource.count<=0) {
                tableView.footer.hidden = YES;
            }else {
                
                tableView.footer.hidden = NO;
            }
        }
      
        if (self.dataSource.count<=0) {
            tableView.loading = NO;
        }
        
    }];
}


#pragma mark - tableView代理

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CWQ_titleContentCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    //设置cell 的分割线
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    cell.content.textColor = [UIColor redColor];
    cell.model = self.dataSource[indexPath.row];
    return cell;
    
}

#pragma mark - 滑动代理
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    /**
     *  这里的偏移量是纵向从contentInset算起 则一开始偏移就是0 向下为负 上为正 下拉
     */
    
    // 获取到tableView偏移量
    CGFloat Offset_y = scrollView.contentOffset.y;
    // 下拉 纵向偏移量变小 变成负的
    if ( Offset_y < 0) {
        // 拉伸后图片的高度
        CGFloat totalOffset = pictureHeight - Offset_y;
        // 图片放大比例
        CGFloat scale = totalOffset / pictureHeight;
        CGFloat width = kScreenWidth;
        // 拉伸后图片位置
        _topImageView.frame = CGRectMake(-(width * scale - width) / 2, Offset_y, width * scale, totalOffset);
    }
    
    UILabel *title = [self.view viewWithTag:111111];
    if (Offset_y >= pictureHeight - 64) {
         [self.navBarView setAlpha:1];
        if (title.hidden) {
            title.hidden = NO;
        }
    }else {
        if (!title.hidden) {
            title.hidden = YES;
        }
        [self.navBarView setAlpha:0];
    
    }
}



#ifdef __IPHONE_7_0
- (UIStatusBarStyle)preferredStatusBarStyle
{
    if (_statusBarStyleControl) {
        return UIStatusBarStyleDefault;
    }
    else {
        return UIStatusBarStyleLightContent;
    }
}
- (BOOL)prefersStatusBarHidden
{
    return NO;
}

#endif

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
